<template>
    <el-container>
        <!-- 顶部导航栏 -->
        <el-header class="header">
            <h1 style="padding: 0 20px;">维修人员主页</h1>
            <h3 style="margin-right: 10px">
                累计工时费收入：{{totalTimeCost}} 元
            </h3>
            <el-button type="danger" size="small" @click="handleLogout">退出登录</el-button>
        </el-header>
        <!-- 侧边栏 -->
        <div style="padding: 0 20px; margin-bottom: 20px;">
            <h2 style="padding: 0 20px;">个人信息</h2>
            <el-table :data="[
                { key: '维修人员ID', value: repairPersonInfo.repair_person_id },
                { key: '用户名', value: repairPersonInfo.username },
                { key: '技术能力', value: formatTaskType(repairPersonInfo.specialty) },
                { key: '时薪', value: repairPersonInfo.hourly_rate + ' 元/小时' }
            ]" border class="table-container">
                <el-table-column prop="key" label="属性" />
                <el-table-column prop="value" label="值" />
            </el-table>
        </div>

        <!-- 主内容区域 -->
        <el-main>
            <h2 style="padding: 0 20px;">等待操作的任务</h2>
            <el-table :data="assignmentsWaited" stripe border class="table-container">
                <el-table-column prop="assignment_id" label="任务ID" class="custom-column" />
                <el-table-column prop="order_id" label="工单ID" class="custom-column" />
                <el-table-column prop="task_type" label="任务类型" class="custom-column">
                    <template #default="scope">
                        {{ formatTaskType(scope.row.task_type) }}
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="450px">
                    <template #default="scope">
                        <el-button type="success" size="small"
                            @click="acceptAssignment(scope.row.assignment_id)">同意</el-button>
                        <el-button type="danger" size="small" @click="refuseAssignment(scope.row.assignment_id)"
                            style="margin-left: 10px">拒绝</el-button>
                    </template>

                </el-table-column>
                                <el-table-column label="催单情况" class="custom-column">
                    <template #default="scope">
                        <div style="display: flex; justify-content: space-between; align-items: center;">
                            <span>{{ getRemindStatus(scope.row.assignment_id) }}</span>
                            <el-button type="primary" size="small"
                                :disabled="getRemindCount(scope.row.assignment_id) === 0"
                                @click="dealRemindRecord(scope.row.assignment_id)">
                                已知晓
                            </el-button>
                        </div>
                    </template>
                </el-table-column>
                
            </el-table>

            <h2 style="padding: 0 20px;">等待完成的任务</h2>
            <el-table :data="assignmentsOperating" stripe border class="table-container">
                <el-table-column prop="assignment_id" label="任务ID" class="custom-column" />
                <el-table-column prop="order_id" label="工单ID" class="custom-column" />
                <el-table-column prop="task_type" label="任务类型" class="custom-column">
                    <template #default="scope">
                        {{ formatTaskType(scope.row.task_type) }}
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="450px" #default="scope">
                    <div style="display: flex; gap: 10px;">
                        <el-button type="success" size="small"
                            @click="logMaterial(scope.row.assignment_id)">登记材料</el-button>
                        <el-button type="primary" size="small"
                            @click="getMaterial(scope.row.assignment_id)">查看材料</el-button>
                        <el-button type="info" size="small" @click="logTime(scope.row.assignment_id)">登记工时</el-button>
                        <el-button type="danger" size="small"
                            @click="updateAssignment(scope.row.assignment_id)">完成任务</el-button>
                    </div>
                </el-table-column>
                <el-table-column label="催单情况" class="custom-column">
                    <template #default="scope">
                        <div style="display: flex; justify-content: space-between; align-items: center;">
                            <span>{{ getRemindStatus(scope.row.assignment_id) }}</span>
                            <el-button type="primary" size="small"
                                :disabled="getRemindCount(scope.row.assignment_id) === 0"
                                @click="dealRemindRecord(scope.row.assignment_id)">
                                已知晓
                            </el-button>
                        </div>
                    </template>
                </el-table-column>
            </el-table>

            <h2 style="padding: 0 20px;">已完成的任务</h2>
            <el-table :data="assignmentsCompleted" stripe border class="table-container">
                <el-table-column prop="assignment_id" label="任务ID" class="custom-column" />
                <el-table-column prop="order_id" label="工单ID" class="custom-column" />
                <el-table-column prop="task_type" label="任务类型" class="custom-column">
                    <template #default="scope">
                        {{ formatTaskType(scope.row.task_type) }}
                    </template>
                </el-table-column>
                <el-table-column prop="score" label="评分" class="custom-column">
                    <template #default="scope">
                        {{ scope.row.score === 0 || !scope.row.score ? '用户未评分' : scope.row.score }}
                    </template>
                </el-table-column>
                <el-table-column prop="time_cost" label="工时费收入" class="custom-column" />
            </el-table>
        </el-main>
    </el-container>

    <!-- 弹出框 -->
    <el-dialog title="登记材料" v-model="dialogVisible" width="30%">
        <el-form>
            <el-form-item label="材料名称">
                <el-select v-model="selectedPart" placeholder="请选择材料">
                    <el-option v-for="part in partList" :key="part.part_id" :label="part.part_name"
                        :value="part.part_name" />
                </el-select>
            </el-form-item>
            <el-form-item label="材料数量">
                <el-input v-model="partQuantity" type="number" min="1" placeholder="请输入数量"
                    @change="validatePartQuantity" />
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button type="primary" @click="confirmLogMaterial">确认</el-button>
                <el-button @click="dialogVisible = false">取消</el-button>
            </div>
        </template>
    </el-dialog>

    <el-dialog title="查看材料" v-model="viewMaterialDialogVisible" width="40%">
        <el-table :data="loggedMaterialList" :key="tableKey" stripe border>
            <el-table-column prop="materialUsageId" label="材料使用ID" />
            <el-table-column prop="partName" label="材料名称" />
            <el-table-column prop="quantity" label="数量" />
        </el-table>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="viewMaterialDialogVisible = false">关闭</el-button>
            </div>
        </template>
    </el-dialog>

    <el-dialog title="登记工时" v-model="logTimeDialogVisible" width="40%">
        <div style="display: flex; align-items: center;">
            <h4 style="margin-right: 10px;">当前总工时：</h4>
            <p>{{ currentWorkTime }}</p>
        </div>
        <el-form>
            <el-form-item label="工时">
                <el-input v-model="workHours" type="number" min="1" placeholder="请输入工时" @change="validateTimeLogged" />
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button type="primary" @click="confirmLogTime">确认</el-button>
                <el-button @click="logTimeDialogVisible = false">取消</el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup>
// TODO: 页面会因为多次刷新而报错，应该是el-table的问题
import { ref, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { getRepairPersonApi,getRepairPersonDTOApi } from '@/api/user';
import {
    acceptAssignmentApi, completeAssignmentApi, getAssignmentByIdApi,
    getAssignmentsByRepairPersonIdAndStatusApi,
    logTimeApi,
    refuseAssignmentApi,getRemindRecordApi,dealRemindRecordApi
} from '@/api/order';
import router from "@/router";
import { getPartByTaskTypeApi } from "@/api/part";
import { createMaterialUsageApi, getUsageByAssignmentIdApi } from "@/api/materialUsage";

// 从代码库 TaskType 枚举获取维修类型（与后端保持一致）
// const taskTypes = ['PAINTER', 'WELDER', 'MECHANIC', 'ELECTRICIAN'];
const typeLabelMap = {
    PAINTER: '漆工',
    WELDER: '焊工',
    MECHANIC: '机修',
    ELECTRICIAN: '电工'
};

const userInfo = localStorage.getItem('userInfo');
const userId = ref(null);

// 登记工时显示
const logTimeDialogVisible = ref(false);
// 登记的时长，最少为1
const workHours = ref(1);
// 提交登记时长
const confirmLogTime = async () => {
    try {
        const res = await logTimeApi(currentAssignmentId.value, workHours.value)
        if (res.data) {
            ElMessage.success('登记成功');
            window.location.reload();
        } else {
            ElMessage.error('登记失败');
        }
    } catch (error) {
        ElMessage.error('网络请求失败');
    } finally {
        logTimeDialogVisible.value = false;
        window.location.reload();
    }
}
// 已经登记的工时
const currentWorkTime = ref(0);
// 登记工时
const logTime = async (assignmentId) => {
    try {
        const res = await getAssignmentByIdApi(assignmentId);
        if (res.data) {
            currentWorkTime.value = res.data.hours_worked;
        } else {
            ElMessage.error('获取工时失败');
        }
    } catch (error) {
        ElMessage.error('网络请求失败');
    }
    currentAssignmentId.value = assignmentId;
    logTimeDialogVisible.value = true;
};
// 监控登记的工时数量大于等于1
const validateTimeLogged = () => {
    if (workHours.value < 1) {
        workHours.value = 1;
        ElMessage.warning('登记的工时至少为1');
    }
    if (workHours.value !== Math.floor(workHours.value)) {
        workHours.value = Math.max(1, Math.floor(workHours.value || 1));
    }
};

// 维修人员信息
const repairPersonInfo = ref({
    repair_person_id: 0,
    username: '',
    specialty: '',
    hourly_rate: 0
});

// 累计工时费收入
const totalTimeCost = ref(0)
// 根据工种查询到的零件列表
const partList = ref([]);
// 根据任务id查询到的已经登记的材料列表
const loggedMaterialList = ref([]);
// 控制查看材料弹出框显示
const viewMaterialDialogVisible = ref(false);
// 控制表格刷新
const tableKey = ref(0);

// 当前激活的assignment_id
const currentAssignmentId = ref(-1);

// 控制弹出框显示
const dialogVisible = ref(false);
// 用户选择的材料和数量
const selectedPart = ref('');
const partQuantity = ref(1);

// 当前分配的任务列表
const assignmentsWaited = ref([]);

// 等待完成的任务列表
const assignmentsOperating = ref([]);

//
const assignmentsCompleted = ref([]);

const remindStatusMap = {
    0: '无催单',
    1: '紧急',
    2: '非常紧急',
    3: '严重紧急'
};

// 存储催单次数的响应式对象
const remindCounts = ref({});

// 获取催单次数的方法
const getRemindCount = (assignmentId) => {
    return remindCounts.value[assignmentId] || 0;
};


// 格式化任务类型
const formatTaskType = (type) => {
    return typeLabelMap[type] || type;
};

// 打开弹出框
const logMaterial = (assignmentId) => {
    console.log('登记按钮被点击');
    currentAssignmentId.value = assignmentId;
    dialogVisible.value = true;
    console.log(dialogVisible.value);
};

// 控制表格刷新
const refreshTable = () => {
    tableKey.value += 1;
};

// 查看已经提交的材料
const getMaterial = async (assignmentId) => {
    try {
        const res = await getUsageByAssignmentIdApi(assignmentId);
        if (res.data) {
            if (Array.isArray(res.data) && res.data.length === 0) {
                ElMessage.warning('该任务目前没有登记材料');
                return;
            }
            loggedMaterialList.value = res.data;
            refreshTable();
            viewMaterialDialogVisible.value = true; // 打开弹出框
        } else {
            ElMessage.error('获取材料失败');
        }
    } catch (error) {
        ElMessage.error('网络请求失败');
    }
}

// 提交材料
const confirmLogMaterial = async () => {
    try {
        if (currentAssignmentId.value === -1) {
            ElMessage.error("请先选择任务");
            return;
        }
        if (!selectedPart.value) {
            ElMessage.error("请选择材料");
            return;
        }
        if (partQuantity.value < 1) {
            ElMessage.error("材料数量至少为1");
            return;
        }
        const res = await createMaterialUsageApi({
            assignmentId: currentAssignmentId.value,
            partName: selectedPart.value,
            quantity: partQuantity.value
        });
        if (res.data) {
            ElMessage.success('登记成功');
            dialogVisible.value = false;
            // 重新加载页面
            window.location.reload();
        } else {
            ElMessage.error('登记失败');
        }
    } catch (error) {
        ElMessage.error('网络请求失败');
    }
}

// 监控材料数量大于等于1
const validatePartQuantity = () => {
    if (partQuantity.value < 1) {
        partQuantity.value = 1;
        ElMessage.warning('材料数量至少为1');
    }
    if (partQuantity.value !== Math.floor(partQuantity.value)) {
        partQuantity.value = Math.max(1, Math.floor(partQuantity.value || 1));
    }
};

const handleLogout = () => {
    localStorage.clear();
    router.push('/login');
    ElMessage.success('已退出登录');
};

// 生命周期：加载维修人员信息和工单
onMounted(async () => {
    if (userInfo) {
        const parsedUserInfo = JSON.parse(userInfo);
        userId.value = parsedUserInfo.user_id; // 假设用户信息对象中有 id 属性
        console.log('userId:', userId.value);
    } else {
        console.log('userInfo 不存在');
        await router.push('/login');
        return;
    }
    try {
        // 获取维修人员信息
        const res1 = await getRepairPersonDTOApi(userId.value);
        repairPersonInfo.value = res1.data;
        console.log(repairPersonInfo.value)

        // 获取分配的工单
        const res2 = await getAssignmentsByRepairPersonIdAndStatusApi(repairPersonInfo.value.repair_person_id, 'ASSIGNED');
        assignmentsWaited.value = res2.data;
        assignmentsWaited.value.forEach(async (assignment) => {
        try {
            const res = await getRemindRecordApi(assignment.assignment_id);
            remindCounts.value[assignment.assignment_id] = res.data.reminder_count || 0;
        } catch {
            remindCounts.value[assignment.assignment_id] = 0;
        }
    });

        // 获取等待完成的工单
        const res3 = await getAssignmentsByRepairPersonIdAndStatusApi(repairPersonInfo.value.repair_person_id, 'IN_PROGRESS');
        assignmentsOperating.value = res3.data;

        assignmentsOperating.value.forEach(async (assignment) => {
        try {
            const res = await getRemindRecordApi(assignment.assignment_id);
            remindCounts.value[assignment.assignment_id] = res.data.reminder_count || 0;
        } catch {
            remindCounts.value[assignment.assignment_id] = 0;
        }
    });

        const res5 = await getAssignmentsByRepairPersonIdAndStatusApi(repairPersonInfo.value.repair_person_id, 'COMPLETED');
        assignmentsCompleted.value = res5.data;
        console.log(assignmentsCompleted.value);

        // 根据工种获取零件列表
        const res4 = await getPartByTaskTypeApi(repairPersonInfo.value.specialty);
        partList.value = res4.data;

        totalTimeCost.value = 0;
        for (const assignment of assignmentsCompleted.value) {
            totalTimeCost.value += assignment.time_cost || 0;
        }
    } catch (error) {
        ElMessage.error('加载数据失败，请稍后再试');
    }
});

const updateAssignment = async (assignmentId) => {
    try {
        const res = await completeAssignmentApi(assignmentId);
        if (res.data) {
            ElMessage.success('已完成该工单');
            // 重新加载页面
            window.location.reload();
        } else {
            ElMessage.error('完成工单失败');
        }
    } catch (error) {
        ElMessage.error('网络请求失败');
    }
};

// 同意工单
const acceptAssignment = async (assignmentId) => {
    try {
        const res1 = await getRepairPersonApi(userId.value);
        repairPersonInfo.value = res1.data;
        const res = await acceptAssignmentApi(repairPersonInfo.value.repair_person_id, assignmentId);
        if (res.data) {
            ElMessage.success('已同意该工单');
            // 重新加载工单列表
            const newRes = await getAssignmentsByRepairPersonIdAndStatusApi(repairPersonInfo.value.repair_person_id, 'ASSIGNED');
            const newRes2 = await getAssignmentsByRepairPersonIdAndStatusApi(repairPersonInfo.value.repair_person_id, 'IN_PROGRESS');
            assignmentsWaited.value = newRes.data;
            assignmentsOperating.value = newRes2.data;
        } else {
            ElMessage.error('同意工单失败');
        }
    } catch (error) {
        ElMessage.error('网络请求失败');
    }
};

// 拒绝工单
const refuseAssignment = async (assignmentId) => {
    try {
        const res1 = await getRepairPersonApi(userId.value);
        repairPersonInfo.value = res1.data;
        const res = await refuseAssignmentApi(repairPersonInfo.value.repair_person_id, assignmentId);
        if (res.data) {
            ElMessage.success('已拒绝该工单');
            // 重新加载工单列表
            const newRes = await getAssignmentsByRepairPersonIdAndStatusApi(repairPersonInfo.value.repair_person_id, 'ASSIGNED');
            assignmentsWaited.value = newRes.data;
        } else {
            ElMessage.error('拒绝工单失败');
        }
    } catch (error) {
        ElMessage.error('网络请求失败');
    } 3
};

// 获取催单状态显示文本
const getRemindStatus = (assignmentId) => {
    return remindStatusMap[getRemindCount(assignmentId)] || '无催单';
};


// 处理已知晓按钮点击
const dealRemindRecord = async (assignmentId) => {
    try {
        const res = await dealRemindRecordApi(assignmentId);
        if (res.data) {
            ElMessage.success('催单已处理');
            remindCounts.value[assignmentId] = 0; // 重置催单次数
        }
    } catch (error) {
        ElMessage.error('处理催单失败');
    }
};
</script>

<style scoped>
.custom-column {
    width: 400px;
}

.header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
}

.dialog-footer {
    text-align: right;
}

.table-container {
    padding: 0 20px;
    /* 增加左右间距 */
}
</style>